package com.tanhua.server.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.common.service.PicUploadService;
import com.tanhua.common.utils.UserThreadLocal;
import com.tanhua.common.vo.ErrorResult;
import com.tanhua.common.vo.PicUploadResult;
import com.tanhua.dubbo.api.QuanZiApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.VideoApi;
import com.tanhua.dubbo.pojo.UserInfo;
import com.tanhua.dubbo.pojo.Video;
import com.tanhua.dubbo.vo.PageInfo;
import com.tanhua.server.config.DefaultConfig;
import com.tanhua.server.vo.PageResult;
import com.tanhua.server.vo.VideoVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class VideoService {

    @DubboReference(version = "1.0.0")
    private VideoApi videoApi;

    @Autowired
    private PicUploadService picUploadService;

    @Autowired
    protected FastFileStorageClient storageClient;

    @Autowired
    private FdfsWebServer fdfsWebServer;

    @DubboReference(version = "1.0.0")
    private UserInfoApi userInfoApi;

    @Autowired
    private VideoMQService videoMQService;

    @Autowired
    private DefaultConfig defaultConfig;

    @DubboReference(version = "1.0.0")
    private QuanZiApi quanZiApi;

    @Autowired
    private QuanZiService quanZiService;



    public Object saveVideo(MultipartFile picFile, MultipartFile videoFile) {
        Long userId = UserThreadLocal.get();

        Video video = new Video();
        video.setUserId(userId);

        //上传图片
        PicUploadResult uploadResult = this.picUploadService.upload(picFile);
        if (StrUtil.isEmpty(uploadResult.getName())) {
            return ErrorResult.builder().errCode("500")
                    .errMessage("上传视频封面图片失败，请重试！").build();
        }

        video.setPicUrl(uploadResult.getName()); //图片

        try {
            //上传小视频
            String fileExtName = StrUtil.subAfter(videoFile.getOriginalFilename(), '.', true);
            StorePath storePath = this.storageClient.uploadFile(videoFile.getInputStream(), videoFile.getSize(), fileExtName, null);
            video.setVideoUrl(fdfsWebServer.getWebServerUrl() + storePath.getFullPath());
        } catch (Exception e) {
            log.error("上传视频文件失败，userId = {}, file = {}", userId, videoFile.getOriginalFilename(), e);
            return ErrorResult.builder().errCode("501")
                    .errMessage("上传视频文件失败，请重试！").build();
        }

        String videoId = this.videoApi.saveVideo(video);
        if (StrUtil.isEmpty(videoId)) {
            return ErrorResult.builder().errCode("502")
                    .errMessage("保存小视频数据失败，请重试！").build();
        }
        //发送发布成功的消息
        this.videoMQService.videoMsg(videoId);

        return null;
    }

    /**
     * 查询小视频列表
     *
     * @param page
     * @param pageSize
     * @return
     */
    public PageResult queryVideoList(Integer page, Integer pageSize) {
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);

        Long userId = UserThreadLocal.get();
        PageInfo<Video> pageInfo = this.videoApi.queryVideoList(userId, page, pageSize);
        List<Video> records = pageInfo.getRecords();

        if (CollUtil.isEmpty(records)) {

            //根据推荐列表查询视频
            List<VideoVo> videoVoList = new ArrayList<>();
            List<Long> videoList = Arrays.asList(this.defaultConfig.getVideoId());

            records = this.videoApi.queryVideoByIdDefault(videoList,page,pageSize);
        }

        //查询用户信息
        Map<Long, UserInfo> userInfoMap =
                this.userInfoApi.queryMapByUserIdList(CollUtil.getFieldValues(records, "userId"));

        List<VideoVo> videoVoList = new ArrayList<>();
        records.forEach(video -> {
            VideoVo videoVo = BeanUtil.toBeanIgnoreError(video, VideoVo.class);
            UserInfo userInfo = userInfoMap.get(video.getUserId());
            BeanUtil.copyProperties(userInfo, videoVo, "id");
            videoVo.setHasFocus(this.videoApi.isFollowUser(userId, userInfo.getUserId()) ? 1: 0);
            videoVo.setHasLiked(this.quanZiApi.queryUserIsLike(userId, videoVo.getId()) ? 1 : 0); //是否点赞（1是，0否）
            videoVo.setLikeCount(Convert.toInt(this.quanZiApi.queryLikeCount(videoVo.getId())));//点赞数
            videoVo.setCommentCount(Convert.toInt(this.quanZiApi.queryCommentCount(videoVo.getId()))); //评论数
            videoVoList.add(videoVo);
        });

        pageResult.setItems(videoVoList);
        return pageResult;
    }


    public Long likeComment(String publishId) {
        Long userId = UserThreadLocal.get();
        Boolean result = this.quanZiApi.likeComment(userId, publishId);

        if (!result) {
            return 0L;
        }

        return this.quanZiApi.queryLikeCount(publishId);
    }

    public Long disLikeComment(String publishId) {
        Long userId = UserThreadLocal.get();
        //取消点赞
        Boolean result = this.quanZiApi.disLikeComment(userId, publishId);
        if (result) {
            //查询点赞数
            return this.quanZiApi.queryLikeCount(publishId);
        }
        return 0L;
    }

    public PageResult queryCommentList(String id, Integer page, Integer pageSize) {
        return this.quanZiService.queryCommentList(id, page, pageSize);
    }

    public void saveComments(String id, String comment) {
        this.quanZiService.saveComments(id ,comment);
    }

    public Object userFocus(Long uid) {
        Long userId = UserThreadLocal.get();
        return this.videoApi.followUser(userId, uid);
    }

    public Object userUnFocus(Long uid) {
        Long userId = UserThreadLocal.get();
        return this.videoApi.disFollowUser(userId, uid);
    }
}
